package com.yuncheng.spcyApi.partyService;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuncheng.spcyApi.bo.PartyDfParamBo;
import com.yuncheng.spcyApi.constant.common.LogConstant;
import com.yuncheng.spcyApi.constant.common.SpcyCommonConstant;
import com.yuncheng.spcyApi.constant.common.SpcyConstant;
import com.yuncheng.spcyApi.entity.PartyRsDfjnjl;
import com.yuncheng.entity.YcSysUser;
import com.yuncheng.exception.BusinessException;
import com.yuncheng.spcyApi.service.IPartyRsDfjnjlService;
import com.yuncheng.spcyApi.service.ISpcyLogService;
import com.yuncheng.spcyApi.service.IYcSysUserService;
import com.yuncheng.spcyApi.utils.DateConvert;
import com.yuncheng.spcyApi.utils.OrderItemUtils;
import com.yuncheng.vo.HttpResult;
import com.yuncheng.spcyApi.vo.common.OrderItemVo;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import utils.DateConversionUtils;
import utils.ExcelUtils;
import utils.LogUtils;
import utils.ObjectToMapUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.InvocationTargetException;
import java.util.*;

@Component(value = "partyDfjnjlService")
public class PartyDfService {

    @Resource
    @Lazy
    private IPartyRsDfjnjlService partyRsDfjnjlService;

    @Resource
    @Lazy
    private IYcSysUserService sysUserService;

    @Resource
    @Lazy
    private ISpcyLogService spcyLogService;

    /**
     * 分页查询
     */
    public HttpResult<?> queryDfjlPageList(PartyRsDfjnjl query, Integer pageNo, Integer pageSize, OrderItemVo orderItemVo) {
        Page<PartyRsDfjnjl> page = new Page<>(pageNo, pageSize);
        LambdaQueryWrapper<PartyRsDfjnjl> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(query.getFuserid()), PartyRsDfjnjl::getFuserid, query.getFuserid());
        queryWrapper.eq(StringUtils.isNotBlank(query.getFgzjlid()), PartyRsDfjnjl::getFgzjlid, query.getFgzjlid());
        queryWrapper.eq(StringUtils.isNotBlank(query.getFjffs()), PartyRsDfjnjl::getFjffs, query.getFjffs());
        queryWrapper.like(StringUtils.isNotBlank(query.getFjfry()), PartyRsDfjnjl::getFjfry, query.getFjfry());
        queryWrapper.eq(StringUtils.isNotBlank(query.getFjfzt()), PartyRsDfjnjl::getFjfzt, query.getFjfzt());

        if (StringUtils.isBlank(orderItemVo.getOrderItem())) {
            queryWrapper.orderByDesc(PartyRsDfjnjl::getCreateTime);
        }else {
            OrderItemUtils.setOrderItem(queryWrapper, orderItemVo);
        }
        IPage<PartyRsDfjnjl> pageList = partyRsDfjnjlService.page(page, queryWrapper);
        return HttpResult.ok(pageList);
    }

    /**
     * 添加党费记录
     * @param dfjnjl
     * @return
     */
    public PartyRsDfjnjl addDfjl(PartyRsDfjnjl dfjnjl){
        if (StringUtils.isBlank(dfjnjl.getFuserid())){
            throw new BusinessException("请选择缴费人员！");
        }

        YcSysUser user = sysUserService.getById(dfjnjl.getFuserid());
        if (user == null){
            throw new BusinessException("当前人员不存在！");
        }
        dfjnjl.setFjfry(user.getRealname());

        dfjnjl.setFjfzt(SpcyCommonConstant.DF_JNJL_JFZT_DJF);
        partyRsDfjnjlService.save(dfjnjl);

        String log = LogUtils.MapToStringMethod(ObjectToMapUtils.objectToMap(dfjnjl));
        spcyLogService.addLogs(LogConstant.LOGS_QY_INFO, log, dfjnjl.getId() + "@" + dfjnjl.getFuserid(), "添加党费记录", SpcyConstant.LOGS_SYS_TYPE_XZ);


        return dfjnjl;
    }

    /**
     * 修改党费记录
     * @param buffer
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     */
    public PartyRsDfjnjl updateDfjl(HashMap<String, String> buffer) throws InvocationTargetException, IllegalAccessException{
        if (StringUtils.isEmpty(buffer.get("id"))){
            throw new BusinessException("操作失败，数据参数为空！");
        }
        String wjmlId = buffer.get("id");
        PartyRsDfjnjl updateBean = partyRsDfjnjlService.getById(wjmlId);
        if (updateBean == null){
            throw new BusinessException("操作失败，没有相匹配的数据！");
        }

        Map<String, Object> oldMap = ObjectToMapUtils.objectToMap(updateBean);
        ConvertUtils.register(new DateConvert(), java.util.Date.class);
        // 自动完成页面到bean的数据对接
        BeanUtils.populate(updateBean, buffer);

        if (StringUtils.isBlank(updateBean.getFuserid())){
            throw new BusinessException("请选择缴费人员！");
        }

        YcSysUser user = sysUserService.getById(updateBean.getFuserid());
        if (user == null){
            throw new BusinessException("当前人员不存在！");
        }
        updateBean.setFjfry(user.getRealname());

        partyRsDfjnjlService.updateById(updateBean);

        String title = "修改党费记录";
        String operContent = title +": "+ LogUtils.BeanModifyMsg(updateBean,oldMap);

        spcyLogService.addLogs(LogConstant.LOGS_PARTY_DFGL, operContent, updateBean.getId()+"@"+updateBean.getFuserid(),title, SpcyConstant.LOGS_SYS_TYPE_XG);

        return updateBean;
    }

    /**
     * 删除党费记录
     * @param id
     */
    public void deleteDfjl(String id){
        if (StringUtils.isBlank(id)){
            throw new BusinessException("数据参数为空！");
        }
        PartyRsDfjnjl bean = partyRsDfjnjlService.getById(id);
        if (bean == null){
            throw new BusinessException("没有想匹配的数据！");
        }
        boolean flag = partyRsDfjnjlService.removeById(id);
        if (flag) {
            String log = LogUtils.MapToStringMethod(ObjectToMapUtils.objectToMap(bean));
            spcyLogService.addLogs(LogConstant.LOGS_QY_INFO, log, bean.getId()+"@"+bean.getFuserid(), "删除党费记录", SpcyConstant.LOGS_SYS_TYPE_SC);
        }
    }

    /**
     * 确认缴费
     */
    public void confirmPayment(PartyDfParamBo paramBo){
        if (StringUtils.isBlank(paramBo.getId())){
            throw new BusinessException("数据参数为空！");
        }

        PartyRsDfjnjl bean = partyRsDfjnjlService.getById(paramBo.getId());
        if (bean == null){
            throw new BusinessException("没有想匹配的数据！");
        }

        String log = "提交缴费：";
        log += "缴费人员["+bean.getFjfry()+"];";
        log += "应缴金额["+bean.getFyjje()+"];";
        log += "应缴时间["+bean.getFyjsj()+"];";
        log += "应缴时间["+bean.getFyjsj()+"];";
        log += "缴费状态["+bean.getFjfzt()+"];";

        if (StringUtils.isNotBlank(bean.getFjfzt()) && bean.getFjfzt().equals(SpcyCommonConstant.DF_JNJL_JFZT_DJF)){
            if (StringUtils.isBlank(paramBo.getFsjje())){
                paramBo.setFsjje("0");
            }
            bean.setFjfzt(SpcyCommonConstant.DF_JNJL_JFZT_DRQ);
            bean.setFsjje(paramBo.getFsjje());
            bean.setFjfsj(DateConversionUtils.DateToDays(new Date()));
        }else if (StringUtils.isNotBlank(bean.getFjfzt()) && bean.getFjfzt().equals(SpcyCommonConstant.DF_JNJL_JFZT_DRQ)){
            bean.setFjfzt(SpcyCommonConstant.DF_JNJL_JFZT_YJF);
        }

        partyRsDfjnjlService.updateById(bean);

        spcyLogService.addLogs(LogConstant.LOGS_PARTY_DFGL,log,bean.getId()+"@"+bean.getFuserid(), "确认缴费",SpcyConstant.LOGS_SYS_TYPE_TJ);

    }

    /**
     * 退回待缴费
     */
    public void returnPayment(String id){
        if (StringUtils.isBlank(id)){
            throw new BusinessException("数据参数为空！");
        }

        PartyRsDfjnjl bean = partyRsDfjnjlService.getById(id);
        if (bean == null){
            throw new BusinessException("没有想匹配的数据！");
        }

        if (StringUtils.isNotBlank(bean.getFjfzt()) && bean.getFjfzt().equals(SpcyCommonConstant.DF_JNJL_JFZT_DRQ)){
            bean.setFjfzt(SpcyCommonConstant.DF_JNJL_JFZT_DJF);
        }else {
            throw new BusinessException("操作失败，无法退回["+bean.getFjfzt()+"]缴费记录！");
        }

        partyRsDfjnjlService.updateById(bean);

        String log = LogUtils.MapToStringMethod(ObjectToMapUtils.objectToMap(bean));
        spcyLogService.addLogs(LogConstant.LOGS_QY_INFO, log, bean.getId()+"@"+bean.getFuserid(), "退回待缴费", SpcyConstant.LOGS_SYS_TYPE_TH);
    }

    /**
     * 导出年度党费记录表-Excel
     */
    public void exportYearDfDataExcel(String year, HttpServletResponse response){
        if (StringUtils.isBlank(year)){
            year = String.valueOf(DateUtil.year(new Date()));
        }
        List<List<String>> resultList = new ArrayList<>();

        // 年度的党费记录
        List<PartyRsDfjnjl> totalYearDfList = partyRsDfjnjlService.list(new LambdaQueryWrapper<PartyRsDfjnjl>()
                .likeRight(PartyRsDfjnjl::getFyjsj, year)
                .orderByDesc(PartyRsDfjnjl::getFjfzt)
                .orderByAsc(PartyRsDfjnjl::getFyjsj));

        // 表头
        String[] titleStrings = new String[]{"序号","姓名","应缴金额","实缴金额","应缴时间","缴费时间","缴费方式","缴费状态"};
        List<String> titleList = CollectionUtil.newArrayList(titleStrings);
        resultList.add(titleList);

        // 数据
        if (CollectionUtil.isNotEmpty(totalYearDfList)){
            List<String> dataList = null;
            int count = 1;
            for (PartyRsDfjnjl df : totalYearDfList){
                dataList = new ArrayList<>(8);
                dataList.add(String.valueOf(count));
                dataList.add(Optional.ofNullable(df.getFjfry()).orElseGet(()->""));
                dataList.add(Optional.ofNullable(df.getFyjje()).orElseGet(()->""));
                dataList.add(Optional.ofNullable(df.getFsjje()).orElseGet(()->""));
                dataList.add(Optional.ofNullable(df.getFyjsj()).orElseGet(()->""));
                dataList.add(Optional.ofNullable(df.getFjfsj()).orElseGet(()->""));
                dataList.add(Optional.ofNullable(df.getFjffs()).orElseGet(()->""));
                dataList.add(Optional.ofNullable(df.getFjfzt()).orElseGet(()->""));
                resultList.add(dataList);
                count++;
            }
        }

        // 文件名称
        String title = year+"-"+"党费";
        ExcelUtils.getLocalTitleExcel(resultList,title,response);
    }
}
